import java.util.Stack;

/**
 * Created with IntelliJ IDEA.
 * Description:逆波兰表达式求值
 * User: 86187
 * Date: 2022-07-29
 * Time: 19:54
 */

public class Test {

    /**
     *该算式转化为常见的中缀算术表达式为：
     *   ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
     * = ((10 * (6 / (12 * -11))) + 17) + 5
     * = ((10 * (6 / -132)) + 17) + 5
     * = ((10 * 0) + 17) + 5
     * = (0 + 17) + 5
     * = 17 + 5
     * = 22
     */
    public static void main(String[] args) {
        String[] tokens = {"10","6","9","3","+","-11","*","/","*","17","+","5","+"};
        System.out.println(evalRPN(tokens));
    }

    private static boolean isOperation(String opera) {
        //判断是不是运算符的函数
        return opera.equals("+") || opera.equals("-") || opera.equals("*") || opera.equals("/");
    }

    public static int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack<>();
        for(String x : tokens) {
            if(!isOperation(x)) {
                //如果是数字字符不是运算符
                stack.push(Integer.parseInt(x)); //将数字字符转换为整数并入栈
            }else {
                //如果是运算符不是数字
                int num2 = stack.pop();
                int num1 = stack.pop();
                switch(x) {
                    case "+" :
                        stack.push(num1+num2);
                        break;
                    case "-" :
                        stack.push(num1-num2);
                        break;
                    case"*" :
                        stack.push(num1*num2);
                        break;
                    case"/" :
                        stack.push(num1/num2);
                        break;
                }
            }
        }

        return stack.pop();
    }
}
